#! /usr/bin/env python

# -*- coding: UTF-8 -*-
# ==============================================================================
# Filename : Highlighter.py
# Purpose  : 
# Author   : Yohann Li (lyh001686@sina.com)
# Date     : 2020-07-01 17:11
# ==============================================================================
from PyQt5.QtCore import QRegularExpression, pyqtSignal
from PyQt5.QtGui import QSyntaxHighlighter, QTextCharFormat, QFont

from conf.configuration import logger, color_pattern, font_style


class Highlighter(QSyntaxHighlighter):
    count_find_text_signal = pyqtSignal(int)

    def __init__(self, parent=None, minimap=False, find_text: str = ''):
        super(Highlighter, self).__init__(parent)
        # logger.debug(f"Setting Hignlighter")
        self.setObjectName('highlighter')
        self.minimap = minimap
        self.find_text = find_text
        self.color_format = {'green': self.set_text_char_format('green'),
                             'red': self.set_text_char_format('red'),
                             'yellow': self.set_text_char_format('yellow'),
                             'grey': self.set_text_char_format('grey')}
        self.pattern = self.set_text_color_pattern()
        self.par = parent

    def highlightBlock(self, text: str) -> None:
        # logger.debug('highlighting')
        block_len = len(text)
        if self.minimap:
            grey_pattern = QRegularExpression('.+')
            grey_match = grey_pattern.match(text)
            self.setFormat(grey_match.capturedStart(), grey_match.capturedLength(),
                           self.color_format.get('grey'))

        i = self.pattern.globalMatch(text)
        while i.hasNext():
            match = i.next()
            cap = match.captured()
            if cap.lower() in ['warning:', 'error:']:
                self.setFormat(match.capturedStart(), block_len,
                               self.color_format.get(color_pattern.get(cap.lower())))
            else:
                self.setFormat(match.capturedStart(), match.capturedLength(),
                               self.color_format.get(color_pattern.get(cap.lower())))

        if self.find_text:
            logger.debug(f"highlighting match {self.find_text}")
            self.color_format.__setitem__('lightyellow', self.set_text_char_format('lightyellow'))
            _pat = QRegularExpression(self.find_text)
            _pat_match_iterator = _pat.globalMatch(text)
            while _pat_match_iterator.hasNext():
                _pat_match = _pat_match_iterator.next()
                self.setFormat(_pat_match.capturedStart(), _pat_match.capturedLength(),
                               self.color_format.get('light', self.set_text_char_format('light')))

    @staticmethod
    def set_text_char_format(color_name: str):
        """设置字体格式:前景色 背景色 加粗"""
        color = font_style.get(color_name)
        _format = QTextCharFormat()
        _format.setFontStyleName(color_name)
        _format.setForeground(color.get('fgc'))
        _format.setBackground(color.get('bgc'))
        _format.setFontWeight(QFont.Bold) if color.get('bold') else ''
        return _format

    @staticmethod
    def set_text_color_pattern():
        _pattert_str = '|'.join([f'\\b{p}\\b' if ':' not in p else p for p in color_pattern.keys()])
        _pattern = QRegularExpression(_pattert_str, options=QRegularExpression.CaseInsensitiveOption)
        return _pattern
